#/usr/bin/python3
#-*- coding:utf-8 -*-

from bot.config.database import MYSQL as config
from pymysql import connect,escape_string,cursors
class modelByMysql:

    def __init__(self,database = None):

        self.config  = config[database]
        self.connect = connect(
            host=self.config['host'],
            user=self.config['user'],
            password=self.config['pass'],
            db=self.config['name'],
            charset=self.config['charset'],
            port=self.config['port'],
            cursorclass=cursors.DictCursor
        )
        self.cursor = None
        self._table = None
        self._where = None
        self._order = None
        self._group = None
        self._limit = None
        self._field = ' * '
        self._query = None

    def table(self,table = None):
        if table is not None and isinstance(table,str):
            self._table = table
            return self
        else:
            print('table value is must and is string!')
            return False

    def where(self,where = None):
        if where is not None and isinstance(where,dict):
            return self.__dealWhere(where)
        return self

    def __dealWhere(self,where):
        self._where = ' where'
        for k,w in enumerate(where):
            if w.find('@') >= 0:
                keys = w.split('@')
                print(keys)
                if keys[1].upper() == 'IN':
                    self._where += " %s.`%s` %s ('%s') " % (self._table,keys[0],keys[1],"','".join(where[w]))
                elif keys[1].upper() == 'LIKE':
                    self._where += " %s.`%s` like '%s' " % (self._table,keys[0],'%'+where[w]+'%')
            else:
                if isinstance(where[w],int):
                    self._where += ' %s.`%s` = %d ' % (self._table,w,where[w])
                else:
                    self._where += " %s.`%s` = '%s' " % (self._table,w,where[w])

            if (k+1) < len(where) and self._where != 'where':
                self._where += 'and'
        return self

    def group(self, group = None):
        if group is not None and isinstance(group,list):
            self._group = " group by %s" % ",".join(group)
        return self

    def order(self, order = None):
        if order is not None and isinstance(order,list):
            self._order = " order by %s" % ",".join(order)
        return self

    def limit(self,start = 0 , size = 20):
        if start >= 0 and size >= 0:
            self._limit = " limit %d,%d" % (start,size)
        return self

    def select(self):
        pass

    def insert(self,data = None):
        if isinstance(data,dict) and self._table:
            self._query = "insert into %s (`%s`) values ('%s')" % (self._table,'`,`'.join(data.keys()),"','".join(data.values()))
            self.cursor = self.connect.cursor()
            self.cursor.execute(self._query)
            result = self.connect.insert_id()
            if result:
                self.connect.commit()
            else:
                self.connect.rollback()
            self.cursor.close()
            return result
        return False

    def update(self):
        pass

    def delete(self):
        pass

    def one(self):
        pass

    def all(self):
        pass
    def query(self,sql=None):
        if sql is not None:
            self.cursor = self.connect.cursor()
            self._query = sql
            self.cursor.execute(self._query)
            result = self.cursor.fetchall()
            if result:
                self.connect.commit()
            else:
                self.connect.rollback()
            self.cursor.close()
            return result
        return []

    def lastQuery(self):
        return self._query